package com.nicefact.mailmonitor.workflow.controller;


import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.nicefact.mailmonitor.core.AppException;
import com.nicefact.mailmonitor.workflow.WorkflowContext;
import com.nicefact.mailmonitor.workflow.WorkflowProcessor;
import com.nicefact.mailmonitor.workflow.entity.Workflow;
import com.nicefact.mailmonitor.workflow.impl.processor.WorkflowStatusType;
import com.nicefact.mailmonitor.workflow.service.WorkflowService;

@Controller
public class WorkflowController {
	
	@Autowired
	ApplicationContext applicationContext;
	
	@Autowired
	WorkflowService workflowService ;
	static Set<String> workflows = new HashSet<String>();
	
	
	@RequestMapping("resource/task/performworkflowtasks.do")
	public void performWorkflow(Model model, HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, InterruptedException {
		Thread.sleep(1000);
		String workflowinstance = request.getParameter("workflowinstanceid");
		if (workflows.add(workflowinstance)) {
			CacheManager cmanager = CacheManager.getInstance();
			Cache cache = cmanager.getCache("WorkflowContextCache");
			WorkflowContext context = (WorkflowContext) cache
					.get(workflowinstance);
			WorkflowProcessor workflowprocessor = (WorkflowProcessor) applicationContext
					.getBean(context.getWorkflowInfo().getWorkflowName());
			workflowprocessor.setContext(context);
			workflowprocessor.doTasks();
		}else{
			System.out.println(workflowinstance + " not running as already run");
		}
	}

	@RequestMapping("/workflow/trigger.do")
	public void triggerWorkflow(HttpServletRequest request) throws AppException {
		String workflowid = request.getParameter("workflowId");
		Key workflowKey = KeyFactory.createKey(Workflow.class.getSimpleName(), Long.parseLong(workflowid));
		Workflow currentWorkflow = (Workflow) workflowService.getById(Workflow.class,workflowKey);
		currentWorkflow.setWorkflowStatus(WorkflowStatusType.INPROGRESS.toString());
		workflowService.updateWorkflow(currentWorkflow);
		workflowService.triggerWorkflow(currentWorkflow);
	}
	
}
